﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LibCommon;
using RTCCore;

namespace LibRTC.Core.MessageMap.ProfileEvent {
    public class ProfileGetHandler : SimpleMessageHandler
    {
        private static ILogger LOGGER = LoggerFactory.GetLogger("ProfileGetHandler", null);

        private RTCCoreClient _coreClient;

        public ProfileGetHandler() {
            _rtcEvent = RTC_EVENT.RTCE_PROFILE;
            _name = "ProfileGetHandler";
        }

        public void SetRTCCoreClient(RTCCoreClient client) {
            Debug.Assert(null != client);
            _coreClient = client;
        }

        public override void Process(RTC_EVENT rtcEventType, object rtcEvent)
        {
            Debug.Assert(RTC_EVENT.RTCE_PROFILE == rtcEventType);
            Debug.Assert(null != rtcEvent);
            Debug.Assert(rtcEvent is IRTCProfileEvent2);

            IRTCProfileEvent2 profileEvent = (IRTCProfileEvent2) rtcEvent;

            if (profileEvent.EventType == RTC_PROFILE_EVENT_TYPE.RTCPFET_PROFILE_GET)
            {
                LOGGER.LogDebug("RTC_PROFILE_EVENT_TYPE.RTCPFET_PROFILE_GET");

                if (RTCHelper.IsSucceeded(profileEvent.StatusCode))
                {
                    _coreClient.Profile = (IRTCProfile2)profileEvent.Profile;
                    _coreClient.Profile.AllowedAuth = RTCSystem.GetInstance().GetSipAuth();
                    _coreClient.Profile.Realm = RTCSystem.GetInstance().GetSipRealm();
                    _coreClient.DoRegister();
                }
                else
                {
                    LOGGER.LogDebug("Logon failed StatusCode" + profileEvent.StatusCode);
                    _coreClient.DoDisablePresence();
                    _coreClient.IPresenceUI.OnLoggedOff();
                    _coreClient.IPresenceUI.ShowMessage("Logon failed!", "Warning");
                }
            }            
        }
    }
}